/**
 * 客户档案管理模块 - Mock API
 * @description 提供客户档案相关的Mock接口
 */

import Mock from 'mockjs'
import { createResponse, createPageResponse } from './index'
import { MOCK_CUSTOMERS, generateCustomerDetail } from './data/customer-dataset'
import logger from '@/utils/logger'

/**
 * 设置客户管理Mock接口
 */
export const setupCustomerMock = (): void => {
  logger.info('[MOCK] 注册客户管理接口...')

  // 1. 获取客户详情 - 必须放在列表接口之前，因为它更具体
  Mock.mock(/\/api\/v1\/customers\/([^\/\?]+)(\?.*)?$/, 'get', (options) => {
    try {
      const urlParts = options.url.split('/')
      const customerId = urlParts[urlParts.length - 1].split('?')[0]
      logger.debug('[MOCK] 客户详情请求:', customerId)
      
      const customer = MOCK_CUSTOMERS.find(c => c.id.toString() === customerId)
      if (customer) {
        // 生成完整的客户详情数据
        const customerDetail = generateCustomerDetail(customer)
        return createResponse(customerDetail, '获取客户详情成功')
      } else {
        return createResponse(null, '客户不存在', 404)
      }
    } catch (error) {
      logger.error('[MOCK] 客户详情接口错误:', error)
      return createResponse(null, '获取客户详情失败', 500)
    }
  })

  // 2. 获取客户列表 - 放在详情接口后面，避免URL匹配冲突
  Mock.mock(/\/api\/v1\/customers(\?.*)?$/, 'get', (options) => {
    try {
      logger.debug('[MOCK] 客户列表请求:', options.url)
      
      const urlParams = new URLSearchParams(options.url.split('?')[1] || '')
      const page = parseInt(urlParams.get('page') || '1')
      const pageSize = parseInt(urlParams.get('pageSize') || '20')
      const keyword = urlParams.get('keyword') || ''
      const customerStatus = urlParams.get('customerStatus') || ''
      const healthStatus = urlParams.get('healthStatus') || ''
      const ageRange = urlParams.get('ageRange') || ''

      let customers = [...MOCK_CUSTOMERS]

      // 搜索过滤
      if (keyword) {
        const searchTerm = keyword.toLowerCase()
        customers = customers.filter(customer => 
          customer.customerName.toLowerCase().includes(searchTerm) ||
          customer.customerCode.toLowerCase().includes(searchTerm) ||
          customer.primaryPhone.includes(searchTerm)
        )
      }

      // 状态过滤
      if (customerStatus) {
        customers = customers.filter(customer => customer.customerStatus === customerStatus)
      }

      if (healthStatus) {
        customers = customers.filter(customer => customer.healthStatus === healthStatus)
      }

      // 年龄过滤
      if (ageRange) {
        if (ageRange === '80+') {
          customers = customers.filter(customer => customer.age >= 80)
        } else {
          const [min, max] = ageRange.split('-').map(Number)
          customers = customers.filter(customer => customer.age >= min && customer.age <= max)
        }
      }

      const total = customers.length
      const start = (page - 1) * pageSize
      const end = start + pageSize
      const paginatedCustomers = customers.slice(start, end)

      logger.debug(`[MOCK] 返回客户数据: ${paginatedCustomers.length}/${total} 条`)

      return createPageResponse(paginatedCustomers, total, page, pageSize)
    } catch (error) {
      logger.error('[MOCK] 客户列表接口错误:', error)
      return createResponse(null, '获取客户列表失败', 500)
    }
  })

  // 3. 创建客户
  Mock.mock('/api/v1/customers', 'post', (options) => {
    try {
      logger.debug('[MOCK] 创建客户请求:', options.body)
      
      const newCustomerData = JSON.parse(options.body)
      const newCustomer = {
        id: `CUST${Date.now()}`,
        customerCode: `CRM${new Date().getFullYear()}${(MOCK_CUSTOMERS.length + 1).toString().padStart(3, '0')}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        lastContactTime: new Date().toISOString(),
        monthlyContactCount: 0,
        tags: [],
        destinationPreference: [],
        budgetRange: '',
        ...newCustomerData
      }
      
      MOCK_CUSTOMERS.unshift(newCustomer)
      
      return createResponse(newCustomer, '创建客户成功', 201)
    } catch (error) {
      logger.error('[MOCK] 创建客户错误:', error)
      return createResponse(null, '创建客户失败', 400)
    }
  })

  // 4. 更新客户
  Mock.mock(/\/api\/v1\/customers\/([^\/\?]+)(\?.*)?$/, 'put', (options) => {
    try {
      const urlParts = options.url.split('/')
      const customerId = urlParts[urlParts.length - 1].split('?')[0]
      logger.debug('[MOCK] 更新客户请求:', customerId)
      
      const updateData = JSON.parse(options.body)
      const customerIndex = MOCK_CUSTOMERS.findIndex(c => c.id.toString() === customerId)
      
      if (customerIndex > -1) {
        MOCK_CUSTOMERS[customerIndex] = {
          ...MOCK_CUSTOMERS[customerIndex],
          ...updateData,
          updatedAt: new Date().toISOString()
        }
        return createResponse(MOCK_CUSTOMERS[customerIndex], '更新客户成功')
      } else {
        return createResponse(null, '客户不存在', 404)
      }
    } catch (error) {
      logger.error('[MOCK] 更新客户错误:', error)
      return createResponse(null, '更新客户失败', 400)
    }
  })

  // 5. 删除客户
  Mock.mock(/\/api\/v1\/customers\/([^\/\?]+)(\?.*)?$/, 'delete', (options) => {
    try {
      const urlParts = options.url.split('/')
      const customerId = urlParts[urlParts.length - 1].split('?')[0]
      logger.debug('[MOCK] 删除客户请求:', customerId)
      
      const customerIndex = MOCK_CUSTOMERS.findIndex(c => c.id.toString() === customerId)
      if (customerIndex > -1) {
        MOCK_CUSTOMERS.splice(customerIndex, 1)
        return createResponse(null, '删除客户成功')
      } else {
        return createResponse(null, '客户不存在', 404)
      }
    } catch (error) {
      logger.error('[MOCK] 删除客户错误:', error)
      return createResponse(null, '删除客户失败', 500)
    }
  })

  // 6. 获取客户统计概览
  Mock.mock(/\/api\/v1\/customers\/statistics\/overview/, 'get', () => {
    try {
      logger.debug('[MOCK] 请求统计数据')
      const statistics = {
        total: MOCK_CUSTOMERS.length,
        active: MOCK_CUSTOMERS.filter(c => c.customerStatus === '有效客户').length,
        potential: MOCK_CUSTOMERS.filter(c => c.customerStatus === '潜在客户').length,
        completed: MOCK_CUSTOMERS.filter(c => c.customerStatus === '已成交客户').length,
        inactive: MOCK_CUSTOMERS.filter(c => c.customerStatus === '无效客户').length,
        blacklist: MOCK_CUSTOMERS.filter(c => c.customerStatus === '黑名单').length,
        growth: Mock.Random.integer(10, 50),
        // 添加CustomerStatistics接口所需的其他字段
        totalCustomers: MOCK_CUSTOMERS.length,
        customerStatusDistribution: {
          '有效客户': MOCK_CUSTOMERS.filter(c => c.customerStatus === '有效客户').length,
          '潜在客户': MOCK_CUSTOMERS.filter(c => c.customerStatus === '潜在客户').length,
          '已成交客户': MOCK_CUSTOMERS.filter(c => c.customerStatus === '已成交客户').length,
          '无效客户': MOCK_CUSTOMERS.filter(c => c.customerStatus === '无效客户').length,
          '黑名单': MOCK_CUSTOMERS.filter(c => c.customerStatus === '黑名单').length
        },
        genderDistribution: {
          '男': MOCK_CUSTOMERS.filter(c => c.gender === '男').length,
          '女': MOCK_CUSTOMERS.filter(c => c.gender === '女').length
        },
        healthStatusDistribution: {
          '健康良好': MOCK_CUSTOMERS.filter(c => c.healthStatus === '健康良好').length,
          '健康一般': MOCK_CUSTOMERS.filter(c => c.healthStatus === '健康一般').length,
          '健康较差': MOCK_CUSTOMERS.filter(c => c.healthStatus === '健康较差').length,
          '健康很差': MOCK_CUSTOMERS.filter(c => c.healthStatus === '健康很差').length
        },
        ageDistribution: {
          '50-60岁': MOCK_CUSTOMERS.filter(c => c.age >= 50 && c.age < 60).length,
          '60-70岁': MOCK_CUSTOMERS.filter(c => c.age >= 60 && c.age < 70).length,
          '70-80岁': MOCK_CUSTOMERS.filter(c => c.age >= 70 && c.age < 80).length,
          '80岁以上': MOCK_CUSTOMERS.filter(c => c.age >= 80).length
        },
        regionDistribution: {
          '北京': Mock.Random.integer(10, 50),
          '上海': Mock.Random.integer(10, 50),
          '广州': Mock.Random.integer(10, 50),
          '深圳': Mock.Random.integer(10, 50)
        }
      }
      
      logger.info('[MOCK] 统计数据:', statistics)
      return createResponse(statistics, '获取统计数据成功')
    } catch (error) {
      logger.error('[MOCK] 统计数据错误:', error)
      return createResponse(null, '获取统计数据失败', 500)
    }
  })

  // 7. 获取客户趋势分析
  Mock.mock(/\/api\/v1\/customers\/statistics\/trends/, 'get', (options) => {
    try {
      logger.debug('[MOCK] 请求趋势分析数据')
      const urlParams = new URLSearchParams(options.url.split('?')[1] || '')
      const period = urlParams.get('period') || 'monthly'
      const dimension = urlParams.get('dimension') || 'customerStatus'
      
      // 根据不同维度生成趋势数据
      const trendsData = {
        period,
        dimension,
        data: []
      }
      
      if (period === 'monthly') {
        // 生成12个月的趋势数据
        for (let i = 11; i >= 0; i--) {
          const date = new Date()
          date.setMonth(date.getMonth() - i)
          const monthStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
          
          trendsData.data.push({
            period: monthStr,
            value: Mock.Random.integer(10, 100),
            growth: Mock.Random.float(-20, 30, 1, 2)
          })
        }
      }
      
      return createResponse(trendsData, '获取趋势分析成功')
    } catch (error) {
      logger.error('[MOCK] 趋势分析错误:', error)
      return createResponse(null, '获取趋势分析失败', 500)
    }
  })

  logger.info('[MOCK] 客户管理接口注册完成')
}